package servlet.cart;

import dao.GoodDao;
import entity.Goods;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * 将商品添加到购物车的servlet
 */
@WebServlet("/cart/add")
public class AddToCartServlet extends HttpServlet{
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String gid = request.getParameter("gid") ;
        String gname = request.getParameter("gname") ;
        Integer count = Integer.valueOf(request.getParameter("count")) ;
        GoodDao gd = new GoodDao() ;
        Goods good = gd.loadByRealName(gid) ;
        HttpSession session = request.getSession() ;
        if(Objects.isNull(session.getAttribute("cart"))){
            //如果用户还没有购物车，则新建一个
            Map<Goods , Integer> cart = new HashMap<Goods , Integer>() ;
            //将商品加入到购物车中
            cart.put(good,count) ;
            response.sendRedirect("");
        }else{
            //如果购物车有东西 ,则查询一下是否有相同的商品
            Map<Goods , Integer> cart = (Map<Goods , Integer>)session.getAttribute("cart") ;
            //遍历查找是否有相同的商品
            Set<Goods> obj = cart.keySet() ;
            Iterator<Goods> iterator = obj.iterator() ;
            boolean flag = false ;//设置一个标记，有相同的商品表示true，否则false
            while(iterator.hasNext()){
                Goods g = iterator.next() ;
                if(g.equals(good)){
                    //如果找到相同商品，重写了equals方法，比较的是 gid，则数量加 1
                    cart.replace(g , cart.get(g)+count);
                    //替换session中
                    session.setAttribute("cart" , cart);
                    flag = true ;
                    break ;
                }
            }
            if(!flag){
                //没有找到相同的商品，进行新增
                cart.put(good , count) ;
                //session 替换
                session.setAttribute("cart" , cart);
            }
        }
        response.sendRedirect("");
    }
}
